<?php

namespace Iaem\HomeBundle\Controller;

use Iaem\UserBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;

class DefaultController extends Controller
{
    /**
     * @Template()
     * @return array
     */
    public function indexAction()
    {
        /** @var SecurityContext $securityContext */
        $securityContext = $this->get('security.context');
        $token = $securityContext->getToken();

        if (!is_null($token) && ($token->getUser() instanceof User)) {
            return $this->redirect($this->generateUrl('home_vote'));
        }

        return [];
    }

    /**
     * @Template()
     * @return array
     */
    public function voteAction()
    {
        /** @var SecurityContext $securityContext */
        $securityContext = $this->get('security.context');
        $token = $securityContext->getToken();

        return ($this->get('voter')->canVote($token->getUser()))
            ? ['nextVoteTime' => false]
            : ['nextVoteTime' => $token->getUser()->getLastVotedTime()->getTimestamp()+86405];
    }

    /**
     *
     * @return array
     */
    public function doVoteAction()
    {
        /** @var SecurityContext $securityContext */
        $securityContext = $this->get('security.context');
        $token = $securityContext->getToken();
        
        if ($token && $this->get('voter')->vote($token->getUser())) {
            return new Response(json_encode(['ok' => 'ok']));
        }

        return new Response(json_encode(['error' => 'ok']));
    }

    /**
     * @Template()
     * @return array
     */
    public function finishAction()
    {
        $repo = $this->getDoctrine()->getRepository('HomeBundle:Vote');
        return ['todayVotes' => $repo->getTodayCount()];
    }
}
